﻿using LS.Screening.UI.Common.Controls;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System.Reactive;
using System.Windows;
using System.Windows.Threading;

namespace LS.Screening.UI.Common
{
    /// <summary>
    /// 视图模型泛型类
    /// </summary>
    public abstract class ViewModel : ReactiveObject, IViewModel
    {
        /// <summary>
        /// IsBusy
        /// </summary>
        [Reactive]
        public bool IsBusy { get; set; }

        /// <summary>
        /// BusyMessage
        /// </summary>
        [Reactive]
        public string BusyMessage { get; set; }

        /// <summary>
        /// 用于关闭窗口
        /// </summary>
        public ReactiveCommand<Unit, Unit> CloseWindowCommand { get; }

        /// <summary>
        /// 主线程的Dispatcher
        /// </summary>
        protected static Dispatcher Dispatcher => Application.Current.Dispatcher;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ViewModel()
        {
            CloseWindowCommand = ReactiveCommand.Create(() => Close());
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public virtual async Task Init()
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// View退出
        /// </summary>
        public virtual async Task Unload()
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// 关闭窗口的方法
        /// </summary>
        protected void Close()
        {
            // 通过消息或事件通知视图关闭窗口
            Application.Current.Dispatcher.Invoke(() => Application.Current.MainWindow.Close());
        }

        /// <summary>
        /// 弹出窗体
        /// </summary>
        /// <typeparam name="VM"></typeparam>
        /// <param name="title"></param>
        /// <param name="initAction"></param>
        /// <param name="isMode"></param>
        /// <returns></returns>
        protected async Task<VM> ShowDialog<VM>(string title, Action<VM, CurrentWindow> initAction = null, bool isMode = true) where VM : ViewModel, new()
        {
            return await Dispatcher.InvokeAsync(() =>
            {
                VM vm = null;
                var view = this.GetView<VM>();
                CurrentWindow window = WindowExtensions.GetWindow();
                window.Content = view;
                window.Title = title;
                if (isMode)
                {
                    window.ShowDialog();
                }
                else
                {
                    window.Show();
                }
                return vm;
            });
        }
    }
}
